﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Timers;
using WebApplication1.Hubs;
using Microsoft.AspNetCore.SignalR;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IHubContext<ChatHub> hubContext)
        {
            _logger = logger;
            _hubContext = hubContext; //使用依赖注入方式 注入hub的上下文实例, 这是Asp.Net Core自带的方式
        }
        private static System.Timers.Timer aTimer;

        [HttpGet]
        public string Get()
        {
            //方法进来之后开启一个定时器, 定时更新某些数据
            aTimer = new System.Timers.Timer(500);
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;

            return "Hello world";
        }
        private readonly IHubContext<ChatHub> _hubContext;
        private int count = 1;
        private void OnTimedEvent(object sender, ElapsedEventArgs e)
        {
            count++;
            // 在Controller处向客户端发送数据
            _hubContext.Clients.All.SendAsync("refresh", count);
        }
    }
}
